package com.example.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Dict;
import com.example.common.enums.ModuleEnum;
import com.example.common.enums.ResultCodeEnum;
import com.example.controller.domain.SearchContent;
import com.example.entity.*;
import com.example.exception.CustomException;
import com.example.mapper.CommentMapper;
import com.example.mapper.NotebookMapper;
import com.example.mapper.WorksMapper;
import com.example.utils.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 评论表业务处理
 **/
@Service
public class CommentService {

    @Resource
    private CommentMapper commentMapper;
    @Resource
    private ReportService reportService;
    @Resource
    private NotebookMapper notebookMapper;
    @Resource
    private WorksMapper worksMapper;
    @Resource
    private MessagesService messagesService;
    @Resource
    private SearchRedisHelper searchRedisHelper;

    /**
     * 新增评论
     */
    public void add(Comment comment) {
        comment.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
        comment.setDelTag("0");
        Dict ipAndCity= IpUtils.getIPAndCity();
        comment.setLocation(String.valueOf(ipAndCity.get("city")));
        if(SensitiveWordsFilter.isContainsSensitiveWords(comment.getContent(),1))
        {
            throw new CustomException(ResultCodeEnum.SENSITIVE_EXIST);
        }
        commentMapper.insert(comment);
        Messages messages=new Messages();
        messages.setFid(comment.getFid());
        messages.setModule(comment.getModule());
        messages.setOptType(ModuleEnum.COMMENT.getValue());
        String dynamicName;
        if(messages.getModule().equals(ModuleEnum.NOTEBOOK.getValue())){
            Notebook notebook=notebookMapper.selectById(messages.getFid());
            dynamicName=notebook.getTitle();
            messages.setUserId(notebook.getUserId());
        }else{
            Works works=worksMapper.selectById(messages.getFid());
            dynamicName=works.getName();
            messages.setUserId(works.getUserId());
        }
        messagesService.add(messages,dynamicName);
        SearchContent searchContent=new SearchContent();
        searchContent.setName(dynamicName);
        searchContent.setFid(comment.getFid());
        searchContent.setModule(comment.getModule());
        searchRedisHelper.addRedisHotSearch(searchContent,2L);

        // 更新rootId
        if (comment.getPid() == null) {
            comment.setRootId(comment.getId());
        } else {
            Comment pComment = commentMapper.selectById(comment.getPid());  // 根据父节点的id查出对应的父节点对象
            if (pComment != null) {
                comment.setRootId(pComment.getRootId());
            }
        }
        this.updateById(comment);
    }

    /**
     * 递归删除
     */
    public void deleteById(Integer id) {
        this.deepDelete(id);
    }

    private void deepDelete(Integer pid) {
        List<Comment> children = commentMapper.selectByPid(pid);
        commentMapper.deleteById(pid);   // 先执行删除  再去找子节点  然后递归删除
        if (CollUtil.isNotEmpty(children)) {
            for (Comment child : children) {
                deepDelete(child.getId());
            }
        }
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            commentMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(Comment comment) {
        commentMapper.updateById(comment);
    }

    /**
     * 根据ID查询
     */
    public Comment selectById(Integer id) {
        return commentMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<Comment> selectAll(Comment comment) {
        List<Comment> list = commentMapper.selectAll(comment);
        list.forEach(entity->entity.setReleaseTime(TimeUtils.TimestampToDateFormat(entity.getCreateTime())));
        return list;
    }

    /**
     * 分页查询
     */
    public PageInfo<Comment> selectPage(Comment comment, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Comment> list = commentMapper.selectAll(comment);
        list.forEach(entity->entity.setReleaseTime(TimeUtils.TimestampToDateFormat(entity.getCreateTime())));
        return PageInfo.of(list);
    }

    public Integer selectCount(Integer fid, String module) {
        return commentMapper.selectCount(fid, module);
    }

    public List<Comment> selectTree(Integer fid, String module) {
        Integer userId= TokenUtils.getCurrentUser().getId();
        List<Comment> rootList = commentMapper.selectRoot(fid, module);
        for (Comment root : rootList) {
            Integer rootId = root.getRootId();
            List<Comment> children = commentMapper.selectByRootId(rootId);
            children.forEach(entity->{
                List<Report> reportList=reportService.selectReport(entity.getId(), userId, ModuleEnum.COMMENT.getValue());
                entity.setUserReport(CollUtil.isNotEmpty(reportList));
                entity.setReleaseTime(TimeUtils.TimestampToDateFormat(entity.getCreateTime()));
            });
            root.setChildren(children);
        }
        rootList.forEach(entity->{
            List<Report> reportList=reportService.selectReport(entity.getId(), userId, ModuleEnum.COMMENT.getValue());
            entity.setUserReport(CollUtil.isNotEmpty(reportList));
            entity.setReleaseTime(TimeUtils.TimestampToDateFormat(entity.getCreateTime()));
        });
        return rootList;
    }

    public List<Comment> selectWorksAll() {
        return commentMapper.selectWorksAll();
    }
    public List<Comment> selectNotebookAll() {
        return commentMapper.selectNotebookAll();
    }


}